<?php

class users extends Zcontroller {
	
		function __construct() {
			parent::__construct();
			$Z_USER = Zsession::getUserFromSession();
			Zsession::setDataToSession("current_page", "home");	
		}
	
		public function index()
		{   
			$this->load->helper('cookie');
            $this->load->helper('url_helper'); 
             
            if(isset($Z_USER["user_login"]) && $Z_USER["user_login"]!=""){
            	redirect(site_url("main"));
            }else {
            	echo get_cookie("userlogin");
            	$this->load->template("templates/user_general","login","Sign in to gozuka"); 
            }
            
     	}

        function authentication(){
            $this->load->model("m_users");
            $data["page"]="signin"; 
			if(isset($_POST['userlogin']) && $_POST['userlogin']==""){
            		$data['error_message']='<b>Please re-enter your user</b><br/>The User you entered inccorrect. Please try again (make sure your caps lock is off).';
            		$this->load->template("templates/general","login","User sign in",$data);
            }else if(isset($_POST['userpwd']) && $_POST['userpwd']==""){
            		$data['error_message']='<b>Please re-enter your password</b><br/>The Password you entered inccorrect. Please try again (make sure your caps lock is off).';
	            	$this->load->template("templates/general","login","User sign in",$data); 
            }else {
            	$user = $this->m_users->authentication($_POST["userlogin"], $_POST["userpwd"]);
	       	    $success=FALSE;    
	            if($user != null){
	                $success=TRUE;
	                Zsession::setUserToSession($user);
	                $type=Zencryption::encrypt(serialize("classified"));
	                redirect(site_url("users/profiles?type=".$type));
	                //redirect($_REQUEST["current_url"]);
	            } else {
	            	// Alert message user/password not correct
	            	$data['error_message']='<b>Please re-enter your password</b><br/>The Password you entered incorrect. Please try again (make sure your caps lock is off).';
	            	$this->load->template("templates/general","login","User sign in",$data); 
	            	
	            }
             }
        }
        
        function authentication_mini(){
            $this->load->model("m_users");
            $data["page"]="signin"; 
			if(isset($_POST['userlogin']) && $_POST['userlogin']==""){
            		$data['error_message']='<b>Please re-enter your user</b><br/>The User you entered inccorrect. Please try again (make sure your caps lock is off).';
            		$this->load->template("templates/general","login","User sign in",$data);
            }else if(isset($_POST['userpwd']) && $_POST['userpwd']==""){
            		$data['error_message']='<b>Please re-enter your password</b><br/>The Password you entered inccorrect. Please try again (make sure your caps lock is off).';
	            	$this->load->template("templates/general","login","User sign in",$data); 
            }else {
            	$user = $this->m_users->authentication($_POST["userlogin"], $_POST["userpwd"]);
	       	    $success=FALSE;    
	            if($user != null){
	                $success=TRUE;
	                Zsession::setUserToSession($user);
	                $type=Zencryption::encrypt(serialize("classified"));
	                redirect(site_url("users/profiles?type=".$type));
	                //redirect($_REQUEST["current_url"]);
	            } else {
	            	// Alert message user/password not correct
	            	$data['error_message1']='<b>Please re-enter your password</b>';
	            	$this->load->template("templates/general","login","User sign in",$data); 
	            	
	            }
             }
        }
        
        function logout() {
        	Zsession::destroySession();
            //redirect($_SERVER['HTTP_REFERER']); 
            redirect("main");       
        }
        
        function signup(){
       		
       		if(isset($Z_USER["user_id"])){
       			redirect(site_url(main));	
       		}else 	
        	$this->load->model("m_users");      	        	
        	$this->load->helper('email');
       	    $data["page"]="signup";      	    
        	$data['sec_question']=$this->m_users->get_sec_que();
        	$data['getCityProvince']=$this->m_users->getCityProvince();
  			 
            $this->load->template("templates/user_general","register","User sign up ",$data);
        } 
              
        
        function gosignup(){
        	$this->load->model("m_users");
        	$this->load->library('form_validation'); 

		       	//$this->form_validation->set_rules('txtEmail', 'Email', 'required|valid_email|callback_email_unique');
		       	$this->form_validation->set_rules('txtEmail', 'Email', '');
				$this->form_validation->set_rules('txtUser', 'User name', 'required|callback_username_check');
				$this->form_validation->set_rules('txtPwd', 'Password', 'trim|required|matches[txtVpwd]|min_length[5]|max_length[12]');
				$this->form_validation->set_rules('txtVpwd', 'Password Confirmation', 'trim|required');
				$this->form_validation->set_rules('txtFrist', 'First Name', '');
				$this->form_validation->set_rules('txtLast', 'Last Name', '');
				$this->form_validation->set_rules('txtTel', 'Phone number', 'required');
				$this->form_validation->set_rules('cb_city', 'Location', 'required');
				$this->form_validation->set_rules('cboQuestion', 'Question', 'required');
				$this->form_validation->set_rules('txtAn', 'Answer', 'required');
				$this->form_validation->set_rules('captcha', 'Security Code', 'required|callback_captcha_check');
							
	       	    
				if ($this->form_validation->run() == FALSE)
				{	
					$data['sec_question']=$this->m_users->get_sec_que();
					$data['getCityProvince']=$this->m_users->getCityProvince();			
					$data['ErrorUserVerified']="You user name was already taken.";
				    $data['message_errors'] = validation_errors();
					$this->load->template("templates/user_general","register","User sign up ",$data);		
				}else{
					    
						$user_id = $this->m_users->registration($_POST["txtFrist"],	
						$_POST["txtLast"],
						$_POST["txtUser"],
						$_POST["txtEmail"],
						sha1($_POST["txtPwd"]),
						$_POST["txtTel"],
						$_POST["cb_city"],
						$_POST["cboQuestion"],
						$_POST["txtAn"]);		

						//redirect(site_url("users/register_success"));
						
						//after sign up successfull
						$user = $this->m_users->authentication($_POST["txtUser"], $_POST["txtPwd"]);
			       	    $success=FALSE;    
			            if($user != null){
			                $success=TRUE;
			                Zsession::setUserToSession($user);
			                $type=Zencryption::encrypt(serialize("classified"));
			                redirect(site_url("users/profiles?type=".$type));
			            }
	            
    					//echo "Sign up have been sucessfully, click here <a herf=\"".site_url("login")."\">login now</a>".$user_id;
						//redirect(site_url("users/signin"));
						//echo "<script type=\'text/javascript\'>setInterval( \"autosubmit()\", 5000 );function autosubmit(){ document.location=".site_url("users").";}</script>";
				  }
				    					
        }

        function register_success(){
        	$this->load->template("templates/user_general","register_success","Sign up successfully ");
        }
        
		//callback users function in validation
        function username_check(){
        	if($this->m_users->getUserVerified($_POST['txtUser']) != null)
			{	
				$this->form_validation->set_message('username_check', 'The User is not available, Please try again!');
				return FALSE;
			}
        	else
			{
			return TRUE;
			}
        }
        
        //callback email function in validation
        function email_unique(){
        	$email=$this->m_users->getEmail($_POST['txtEmail']);
        	if($email != null)
			{	
				$this->form_validation->set_message('email_unique', 'The email is not available, Please try again!');
				return FALSE;
			}elseif($email=='zuka@gozuka.com'){
				return TRUE;
			}
        	else
			{
			return TRUE;
			}
        }
       
        function captcha_check(){
        	if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) 
			{	
				$request_captcha = htmlspecialchars($_REQUEST['captcha']);
				$captcha_message = "Invalid code, Please try again!";
        		$request_captcha = htmlspecialchars($_REQUEST['captcha']);
				$this->form_validation->set_message('captcha_check', '<div style=\"background-color: #FF606C; width:160px; height:50px; padding:5px;\">'.$captcha_message.'</div>');				

				//$data["captcha_message"]="<div style=\"background-color: #FF606C; width:160px; height:50px; padding:5px;\"><h2>$captcha_message</h2></div>";   				 
				return FALSE;
			}
        	else
			{
			return TRUE;
			}
        }
        
               	
        function forgetPassword(){
        	$data["page"]="signup";	        	
        	$this->load->template("templates/general","forgotPassword","User forgot password! ",$data); 
        	
        }
        
        function sendPassword(){	
        	$this->load->model("m_users");
			$this->load->library('form_validation');
	        $this->load->helper('email');
        	
				$user=$this->m_users->getPassword($_POST["userName"],$_POST["userEmail"]);
	        	if(trim($_POST["userName"])==""){
					$data['message_errors'] = "Username can not be blank";
					$this->load->template("templates/general","forgotPassword","User forgot password! ",$data);
								
	        	}else if($user == null){
					$data['message_errors'] = "User and email is invalid";
					$this->load->template("templates/general","forgotPassword","User forgot password! ",$data);
					
				}else if(trim($_POST["userEmail"])==""){
					$data['message_errors'] = "Email can not be blank";
					$this->load->template("templates/general","forgotPassword","User forgot password! ",$data);	
								
				}else if(!valid_email($_POST["userEmail"])){
					$data['message_errors'] = "Email is invalid";
					$this->load->template("templates/general","forgotPassword","User forgot password! ",$data);
				}else{

				//echo "send mail";
				$config=Array(
		            'protocol' => 'smtp',
		            'smtp_host' => 'ssl://smtp.googlemail.com',
		            'smtp_port' => 465,
		            'smtp_user' => 'noreply.zuka@gmail.com',
		            'smtp_pass' => 'Zuka35250',
					//'smtp_user' => 'allwebkh@gmail.com',
		            //'smtp_pass' => 'goallwebgo',
		            'mailtype'  => 'html',
		            'charset' => 'utf-8',
		            'wordwrap'=>TRUE,		
		        );
		        $param = serialize($_POST['userName']);
		        $this->load->library('email',$config);
		        $this->email->set_newline("\r\n");
		        $this->email->from('noreply.zuka@gmail.com');
		        $this->email->to($_POST['userEmail']);
		        $this->email->subject("Reset your ZUKA password account");
		        $this->email->message("<div>Click here if you want to change the password</div><a href=http://www.gozuka.com/users/resetPassword?e=".Zencryption::encrypt($param).">http://www.gozuka.com/users/resetPassword?e=".Zencryption::encrypt($param)."</a>");
				$result=$this->email->send();
				echo "email has been sent to <font color=\"#BD2031\">".$_POST['userEmail']."</font>, please check your email.";
				}		
        }
        
        /*function unSelectUser(){
        	    $e = "sokleng";
        		$param = serialize($e);
        		redirect(site_url("users/resetPassword?e=".Zencryption::encrypt($param)));
        }*/
        
        function resetPassword(){
        		$this->load->model("m_users");
        		$data["page"]="";	
        		//$users=isset($_GET["e"]) ? $_GET["e"] : null;	         			
        		//$users = Zencryption::decrypt($users);
        		//$users = unserialize($users);
        		$Z_USER = Zsession::getUserFromSession();
	    		$users=$Z_USER["user_id"];
        		
	        	if($this->m_users->getUserVerified1() != null){
	 	        	$data["username"]=$users;
	        		$data["userEmail"]=$this->m_users->getEmailByUser($users);   	    			  
	        		$this->load->template("templates/general","changePassword","User change password! ",$data); 				
	        	}else 
	        		echo "<br/ >User name not fuound, please try again!";
	        		//redirect(site_url("users/forgetPassword"));
        }
        
        function changePassword(){
        	$this->load->model("m_users");
        	$data["page"]="signin";	
        	$this->load->library('form_validation');
	        $this->load->helper('email');
	            $this->form_validation->set_rules('userPwd', 'new password', 'trim|required|matches[userVpwd]');
				$this->form_validation->set_rules('userVpwd', 'verified new password', 'trim|required');
					if ($this->form_validation->run() == FALSE)
					{
						$data['message_errors'] = validation_errors();					
        				$data["userEmail"]=$this->m_users->getEmailByUser($_POST["txtUsername"]);
						$this->load->template("templates/general","changePassword","User change password! ",$data); 
					}else {	
						//update user password
						redirect(site_url("users/updatePassword/".$_POST["txtUsername"]."/".strtolower(sha1($_POST["userPwd"]))));
					}
        	
        }
        
        function updatePassword($users,$pass){
        	$this->load->model("m_users");
        	$this->m_users->updatePassword($users, $pass);
        	echo "Your password has been changed, Please login";
        	redirect(site_url("users/signup"));
        }
        
        function profiles(){
        	$Z_USER = Zsession::getUserFromSession();
        	$this->load->model("m_users");
        	$this->load->model("m_property");
        	$this->load->model("m_classify");
        	$this->load->model("m_jobwanted");
			$this->load->model("job_announcement_model");
       		//if(isset($Z_USER["user_id"])){
       		    $data["users"]=$this->m_users->getProfiles();	
	        	$data["result_pro"]=$this->m_property->get_property_by_user();
	        	$data["announcements"]=$this->job_announcement_model->selectAnnouncementByUserId($Z_USER["user_id"]);
	        	$data["result_class"]=$this->m_classify->get_product_user();
	        	$data["alljobs"]=$this->m_jobwanted->get_current_job_wanted();
	        	$data["success_message"] = Zsession::getFlash("success_message");
	        	$this->load->template("templates/general","profiles","User Profiles! ",$data); 
       				
       		//}else 	
			//	redirect(site_url("users"));
        }
        
        function updateProfile(){
        	$this->load->model("m_users");  	        	
        	$this->load->helper('email');
        	$data["page"]="signin";      	    
        	$data['sec_question']=$this->m_users->get_sec_que();
        	$data['getCityProvince']=$this->m_users->getCityProvince();
        	
        	$users=isset($_GET["e"]) ? $_GET["e"] : null;	         			
        	$users = Zencryption::decrypt($users);
        	$users = unserialize($users);
        	
        	$data["users"]=$this->m_users->getProfiles($users);
        	
        	$this->load->template("templates/user_general","editProfiles","Update User Profiles! ",$data); 
        }
        
        //callback email function in validation
        function email_unique1(){
        	$email=$this->m_users->getPassword($_POST['txtUser'],$_POST['txtEmail']);
        	if($email == null)
			{	
				$this->form_validation->set_message('email_unique1', 'The email not in database., Please try again!');
				return FALSE;
			}
        	else
			{
			return TRUE;
			}
        }
		function ext_check1(){
			return $this->ext_check("image1");
        }
        function ext_check($obj_name) {
        	$allowedExt = array("jpg","jpeg","gif","png","JPG","GIF","PNG","JPEG");
        	switch ($obj_name) {
        		case "image1" : $function_name = "ext_check1"; break;
        		case "image2" : $function_name = "ext_check2"; break;
        		case "image3" : $function_name = "ext_check3"; break;
        		case "image4" : $function_name = "ext_check4"; break;
        		case "image5" : $function_name = "ext_check5"; break;
        		default : $function_name = "ext_check1"; break;
        	}
			
			if (isset($_FILES) && isset($_FILES[$obj_name]) && isset($_FILES[$obj_name]["tmp_name"]) && $_FILES[$obj_name]["tmp_name"]!= "") {
				$file_ext = next(explode(".", $_FILES[$obj_name]["name"]));
				if (!in_array($file_ext, $allowedExt)) {
					$this->form_validation->set_message($function_name, 'The %s (<font color=blue>'.$_FILES[$obj_name]["name"].'</font>) is not an image file.'); 
					return false;
				}
			}
			return true;
        }
        
        function goUpdateProfile(){
        	$this->load->model("m_users"); 
        	$this->load->library('form_validation');
        	$Z_USER = Zsession::getUserFromSession();
        	$data["page"]="signin";
		       	$this->form_validation->set_rules('txtEmail', 'Email', 'required|callback_email_unique1');
				$this->form_validation->set_rules('txtFrist', 'First Name', '');
				$this->form_validation->set_rules('txtUser', 'User name', '');
				$this->form_validation->set_rules('txtLast', 'Last Name', '');
				$this->form_validation->set_rules('txtTel', 'Phone number', 'required');
				$this->form_validation->set_rules('cb_city', 'City/Province', 'required');
				$this->form_validation->set_rules('cboQuestion', 'Question', 'required');
				$this->form_validation->set_rules('txtAn', 'Answer', 'required');
				$this->form_validation->set_rules('txtAn', 'Answer', 'required');
				$this->form_validation->set_rules('image1', 'Picture 1', "callback_ext_check1");
				//$this->form_validation->set_rules('captcha', 'Security Code', 'required');
				
			if ($this->form_validation->run() == FALSE)
			{	
				$data['sec_question']=$this->m_users->get_sec_que();
				$data['getCityProvince']=$this->m_users->getCityProvince();
				$data["users"]=$this->m_users->getProfiles($_POST['txtUser'],$_POST['txtEmail']);
				
				$param = serialize($_POST['txtUser']);
        		        		
				$data['message_errors'] = validation_errors();
				$this->load->template("templates/general","editProfiles","Update User Profiles!",$data); 
				
				//redirect(site_url("users/updateProfile?e=".Zencryption::encrypt($param)));
			}else {	
				//update user profile
				
                $date=date("His");
                $patch=FCPATH."/usr/".htmlspecialchars($Z_USER["user_id"])."/"; /* NB! create this dir! */
                if (!file_exists ($patch)){ mkdir($patch,0755);}
                $config["upload_path"] = $patch;
                $config["allowed_types"] = "gif|jpg|png|bmp|jpeg|JPG";		      
                $config["image_library"] = "gd2";
                $config["source_image"] = $patch.htmlspecialchars($Z_USER["user_id"]);
                $config["encrypt_name"]  = FALSE;
                //$config["overwrite"]  = TRUE;
                $config["max_size"]  = "0";
                $config["max_width"]  = "0";
                $config["max_height"]  = "0";
  
                /* Load the upload library */
                $this->load->library("upload", $config);
          
                /* Create the config for image library */
                /* (pretty self-explanatory) */
                $configThumb = array();
                $configThumb["image_library"] = "gd2";
                //$configThumb["thumb_marker"] = $date."_Thumb";
                //$configThumb["source_image"] = "";
                //$configThumb["create_thumb"] = TRUE;
                //$configThumb["maintain_ratio"] = TRUE;
                //$configThumb["width"] = 68;
                //$configThumb["height"] = 60;
                
                /* Load the image library */
                $this->load->library("image_lib");
                        
                $filename_arr = array();
                $filename_big_arr = array();
                
				  for($i = 1; $i <= count($_FILES); $i++) {
                  /* Handle the file upload */
                  $upload = $this->upload->do_upload("image".$i);
                  /* File failed to upload - continue */
                     
                  if($upload === FALSE) continue;
                      /* Get the data about the file */
                      $data = $this->upload->data();
                  
                      $uploadedFiles[$i] = $data;
                      /* If the file is an image - create a thumbnail */
                      if($data["is_image"] == 1) {
                        $filename_arr["image".$i] = $data["orig_name"];
              
                        //$_FILES["image".$i]['name'];
                        $configThumb["source_image"] = $data["full_path"];     
                        
                        $this->image_lib->initialize($configThumb);
                        $this->image_lib->resize();
                         
                        //echo "<pre>"; var_dump($data); echo "</pre>";
                        $filename = $data["file_path"].$data["raw_name"].$date.$data["file_ext"];
                        //$filename = $data["raw_name"].'_big'.$data['file_ext'];
      
                        rename($data["full_path"], $filename);
                        //rename($data["full_path"], $filename);
                        $filename_big_arr["image".$i] = $data["raw_name"].$date.$data["file_ext"];
                        
                        //$this->m_property->insert_pic_by_id($prop_id,$filename_big_arr["image".$i]);
                        //$file_path='usr/'.htmlspecialchars($Z_USER["user_id"]).'/';
				
		        		$this->m_users->updateProfiles($_POST["txtUser"],
		        								 $_POST["txtFrist"],	
											     $_POST["txtLast"],
												 $_POST["txtTel"],
												 $_POST["cb_city"],
												 $_POST["cboQuestion"],
												 $_POST["txtAn"],
												 $filename_big_arr["image".$i]);			  			  
                      }//end if $data is image
                 
                   } // FOR LOOP

                Zsession::setFlash("success_message", "Profile has been saved successfully");
                redirect(site_url('users/profiles?type='.Zencryption::encrypt(serialize("properties"))));
			    /*echo "<div class=\"sucessfully\"><h3>User profile have been updated sucessfully.</h3></div>";
				$auto="<script type=\"text/javascript\">setInterval( \"autosubmit()\", 1600 );function autosubmit(){ document.location=\"".site_url('users/profiles?type='.Zencryption::encrypt(serialize("properties")))."\";}</script>";
				echo $auto;
				*/ 
			}
        }
        
        
        function test(){
			//echo "Sign up have been sucessfully, click here <a href=\"".site_url("login")."\">login now</a>";
			$this->load->template("templates/general","register_success","Sign up successfully ");
		}
}
?>
